package com.lw.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/4/25 11:30
 */
public class WebsocketServer {
    public static void main(String[] args) {
        //创建线程组对象，用于处理请求
        NioEventLoopGroup parentGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            //创建服务端启动对象
            ServerBootstrap serverBootstrap=new ServerBootstrap();
            serverBootstrap.group(parentGroup,workGroup)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG,128)//使用TCP协议
                    .channel(NioServerSocketChannel.class)//设置通道
                    .childHandler(new WebsocketInitializer());//设置处理器
            //绑定到当前服务器的12345端口
            ChannelFuture channelFuture=serverBootstrap.bind(12345).sync();
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.err.println("启动服务器成功");
                } else {
                    System.err.println("启动服务器失败");
                }
            });
            //等待关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            parentGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
